package com.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
@RestController
@Slf4j
public class ImageController {
    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadImage(@RequestParam("image") MultipartFile image) throws IOException{
        String imageName = UUID.randomUUID().toString() + "_" + image.getOriginalFilename();
        File dest = new File(uploadDir + imageName);
        image.transferTo(dest);
        return ResponseEntity.ok("/api/images/" + imageName);
    }

    @GetMapping("/images/{imageName}")
    public ResponseEntity<Resource> getImage(@PathVariable String imageName) throws IOException {
        File file = new File(uploadDir + imageName);
        Resource resource = new UrlResource(file.toURI());
        return ResponseEntity.ok()
                .contentType(MediaType.IMAGE_JPEG)
                .body(resource);
    }

    @PostMapping("/upload/multi")
    public List<String> handleMultiFileUpload(@RequestBody List<MultipartFile> files) {
        List<String> fileUrls = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                String fileName = UUID.randomUUID().toString() + "_" + file.getOriginalFilename();
                Path filePath = Paths.get(uploadDir + fileName);
                Files.copy(file.getInputStream(), filePath);
                fileUrls.add("/uploads/" + fileName); // 返回文件URL，根据实际情况调整
            } catch (IOException e) {
                // 处理异常，例如记录日志或抛出自定义异常
                e.printStackTrace();
            }
        }
        return fileUrls; // 返回所有上传文件的URL列表
    }
}
